package com.cnbot.aimolib.detect;

import android.graphics.RectF;
import android.graphics.Region;

import com.cnbot.aimolib.bean.AimoOutlineData;
import com.cnbot.aimolib.bean.AimoRawFaceData;
import com.white.loglib.L;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author ytf
 * Created by on 2021/06/05 10:53
 */
public class DefaultDetectStrategy implements IDetectInspectStrategy {

    private Region region = new Region();

    @Override
    public AimoRawFaceData selectFace(List<AimoRawFaceData> list, List<AimoOutlineData> outlines, RectF preview, RectF strictRect) {
        //没有识别到
        if(list == null || list.size() == 0) return null;

        int size = list.size();
        if(size > 1){
            L.e("识别到" + list.size() + "个人脸");
            Collections.sort(list, new Comparator<AimoRawFaceData>() {

                @Override
                public int compare(AimoRawFaceData o1, AimoRawFaceData o2) {

                    return 0;
                }
            });
        }else{
            AimoRawFaceData sample = list.get(0);
            AimoOutlineData outline = outlines.get(0);
            if(strictRect != null){
                region.set((int)strictRect.left, (int)strictRect.top, (int)strictRect.right, (int)strictRect.bottom);
                boolean r1 = region.contains((int)outline.leftEye.x, (int)outline.leftEye.y);
                boolean r2 = region.contains((int)outline.rightEye.x, (int)outline.rightEye.y);
                boolean r3 = region.contains((int)outline.nose.x, (int)outline.nose.y);
                boolean r4 = region.contains((int)outline.rightMouth.x, (int)outline.rightMouth.y);
                boolean r5 = region.contains((int)outline.leftMonth.x, (int)outline.leftMonth.y);
                if(r1 && r2 && r3 && r4 && r5) return sample;
            }else{
                RectF origin = outline.faceRect;
                if(inRectf(origin, preview)){
                    //1/4 - 3/4
                    if(origin.left >= (int)preview.width() >> 2
                        && origin.right <= preview.width() * 0.75f){
                        return sample;
                    }
                }
            }
        }
        return null;
    }

    private boolean inRectf(RectF src, RectF target){
        return target.contains(src);
    }

    private boolean meetsMinAreaDetect(AimoRawFaceData sample, RectF preview){
        RectF sr = sample.getRect();
        return sr.width() * sr.height() >= (int)(preview.width() * preview.height()) >> 3;
    }
}
